<template>
  <div class="user-gender-chart">
    <t-loading :loading="loading">
      <div ref="chartRef" class="chart-container"></div>
      <div v-if="!loading && !data.length" class="empty-data">
        <t-empty description="暂无数据" />
      </div>
    </t-loading>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import type { UserGenderData } from '../../../api/statistics'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
])

const props = defineProps<{
  data: UserGenderData[]
  loading: boolean
}>()

const chartRef = ref<HTMLElement | null>(null)
const chart = ref<echarts.ECharts | null>(null)

// 初始化图表
onMounted(() => {
  if (chartRef.value) {
    chart.value = echarts.init(chartRef.value)
    updateChart()
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (chart.value) {
    chart.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 监听数据变化
watch(() => props.data, updateChart, { deep: true })

// 处理窗口大小变化
const handleResize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

// 获取性别标签
const getGenderLabel = (gender: string) => {
  const genderMap: Record<string, string> = {
    male: '男性',
    female: '女性',
    unknown: '未知'
  }
  return genderMap[gender] || '未知'
}

// 获取性别颜色
const getGenderColor = (gender: string) => {
  const colorMap: Record<string, string> = {
    male: '#0052D9',
    female: '#ED49B4',
    unknown: '#BBBBBB'
  }
  return colorMap[gender] || '#BBBBBB'
}

// 更新图表
const updateChart = () => {
  if (!chart.value || !props.data.length) return
  
  const total = props.data.reduce((sum, item) => sum + item.count, 0)
  
  const pieData = props.data.map(item => ({
    name: getGenderLabel(item.gender),
    value: item.count,
    itemStyle: {
      color: getGenderColor(item.gender)
    }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: pieData.map(item => item.name),
      formatter: (name: string) => {
        const item = pieData.find(d => d.name === name)
        if (item) {
          const percentage = ((item.value / total) * 100).toFixed(1)
          return `${name}: ${item.value} (${percentage}%)`
        }
        return name
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  chart.value.setOption(option)
}
</script>

<style scoped>
.user-gender-chart {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.empty-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 